# coding=utf-8
"""
To simulate the time points at which a machine fails within 1000 hours
 using Python, a random number generator is used to simulate the occurrence of
 failure events. Typically, the machine's failure times can be modeled
 using an exponential distribution or another appropriate distribution,
 depending on the failure model you wish to use. Here's an example of
 simulating basic failure times using Python, with an exponential
 distribution as the model:
"""
import matplotlib.pyplot as plt
import numpy as np


# seed：随机种子
# total_hours：总模拟时间（小时）
# mean_failure_interval：平均故障时间间隔（小时）
def failure_generator(seed=0,
                      total_hours=120 * 8,
                      mean_failure_interval=300):
    # 设置随机数种子以确保可重复性
    np.random.seed(seed)
    # 记录故障时间点的列表
    failure_times = []
    # 模拟故障事件
    current_time = 0
    while current_time < total_hours:
        # 生成下一个故障事件的时间间隔
        time_to_failure = np.random.exponential(mean_failure_interval)
        # 更新当前时间
        current_time += time_to_failure
        # 如果故障时间小于总模拟时间，则记录故障时间点
        if current_time < total_hours:
            failure_times.append(current_time)

    return failure_times


failure_times = failure_generator(4, 120 * 9, 250)

# 将故障时间点可视化
plt.hist(failure_times, bins=30, density=True,
         alpha=0.5, color='b', label='Failure Times')
plt.xlabel('Time (hours)')
plt.ylabel('Probability Density')
plt.title('Machine Failure Simulation')
plt.legend()
plt.show()
